import urlConfig from './config.js'
const request = {}
const headers = {}

request.globalRequest = (url, method, data, power) => {

	/* 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分 */
	switch (power) {
		case 1:
			headers['Content-Type'] = 'multipart/form-data';
			break;
		case 2:
			headers['Content-Type'] = 'application/x-www-form-urlencoded';
			break;
		default:
			headers['Content-Type'] = 'application/json';
			break;
	}
	const xToken = uni.getStorageSync('login_token');
	// 请求头携带的登录凭证
	if (xToken) {

		headers['Authorization'] = xToken;
		// headers['token'] = xToken;
	}
	// 请求头携带的登录凭证
	if (data && data.curToken) {

		headers['Authorization'] = data.curToken;
		// headers['token'] = data.curToken;
	}
	// replaceUrl 截取baseURL
	const baseUrl = urlConfig

	// 请求头携带语言
	const lang = uni.getStorageSync('lang')
	headers['lang'] = lang || 'cn'
	const id = uni.getStorageSync('userId')
	// if (id) {
	// 	headers['tsCustomerId'] = id
	// }
	// headers['tsCustomerId'] = '10502'

	return uni.request({
		url: baseUrl + url,
		method,
		data,
		header: headers,
	}).then((res) => {
		
		if (res && res[1] && res[1].data) {
			// 返回请求结果
			// console.log('res', res[1].data.code)
			if (res[1].data.code !== 200) {
				uni.showToast({
					title: res[1].data.message,
					icon: 'none'
				})
				if (res[1].data.code === 201) {
					// uni.clearStorageSync()
					uni.setStorageSync('login_token', '')
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 800)
				}
			} else {
				return res[1].data
			}
		}
	}).catch((params) => {
		// console.log('params', params)
		switch (params.code) {
			// 判断状态码
			case 201:
				// uni.clearStorageSync()
				uni.setStorageSync('login_token', '');
				uni.showToast({
					title: '未登录，请前往登录',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}, 800)
				break;
			default:
				uni.showToast({
					title: params.message,
					icon: 'none',
				});
				return Promise.reject();
		}
	});
};
export default request
